package com.clf.common.util.remote;

import com.clf.common.util.page.PageQuery;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;

/**
 * 推荐只在远程调用的接口层使用, 即对外提供服务的最外层.<br>
 * 例如:<br>
 * <li>controller - service - dao 这种, 不建议 service 层的返回结果使用 Result, 异常统一在最外层处理.</li>
 * <li>facade - service - dao 这种, 请在 facade 层使用 Result,并且无论任何情况, result 都不能为
 * null.</li>
 *
 * @param <V>
 */
@Data
public class FacadeResult<V> implements Serializable {

    private static final long serialVersionUID = 6781030660269943247L;

    private boolean success = false;

    private V data;

    /**
     * facade接口调用的分页对象，用于保存分页的数据
     */
    private PageQuery pageQuery;

    /**
     * 错误信息
     */
    private String errorMsg;

    /**
     * 业务错误信息代码
     */
    private String errorCode;

    /**
     * 一般是 e.getMessage();
     */
    private String exceptionMsg;

    @Deprecated
    public FacadeResult() {
    }

    public static <T> FacadeResult<T> buildSucc() {
        return buildSucc(null);
    }

    @SuppressWarnings("deprecation")
    public static <T> FacadeResult<T> buildSucc(T data) {
        FacadeResult<T> result = new FacadeResult<>();
        result.setSuccess(true);
        result.setData(data);
        return result;
    }

    public static <T> FacadeResult<T> buildFail(String errorMsg) {
        return buildFail(null, errorMsg);
    }

    public static <T> FacadeResult<T> buildFail(String errorCode, String errorMsg) {
        return buildFail(errorCode, errorMsg, null);
    }

    @SuppressWarnings("deprecation")
    public static <T> FacadeResult<T> buildFail(String errorCode, String errorMsg, String exceptionMsg) {
        FacadeResult<T> result = new FacadeResult<>();
        result.setSuccess(false);
        result.setErrorCode(errorCode);
        result.setErrorMsg(errorMsg);
        result.setExceptionMsg(exceptionMsg);
        return result;
    }

    /**
     * 数据是否为null.
     *
     * @return
     */
    public boolean dataIsNull() {
        return this.data == null;
    }

    /**
     * 数据是否为空.
     *
     * @return
     */
    public boolean dataIsEmpty() {
        if (dataIsNull()) {
            return true;
        }
        return CollectionUtils.sizeIsEmpty(this.data);
    }
}
